<template> 
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right" type="primary" @click="handleSearchList()" size="small">
          查询搜索
        </el-button>
        <el-button style="float:right;margin-right: 15px" @click="handleResetSearch()" size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="规则名称">
            <el-input v-model="listQuery.roleName" class="input-width" placeholder="规则名称"></el-input>
          </el-form-item>
          <el-form-item label="客户端类型">
            <el-select v-model="listQuery.clientId" placeholder="客户端类型" style="width:100%">
              <el-option label="所有类型" value="ALL"></el-option>
              <el-option label="微信" value="WX"></el-option>
              <el-option label="app" value="APP"></el-option>
              <el-option label="网页" value="WEB"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="listQuery.status" placeholder="状态" style="width:100%">
              <el-option label="全部" value="2"></el-option>
              <el-option label="无效" value="0"></el-option>
              <el-option label="有效" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>积分数据列表</span>
      <el-button size="mini" class="btn-add" @click="createActivity()">创建积分</el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="newProductTable" :data="integralList" style="width: 100%;"
        @selection-change="handleSelectionChange" v-loading="listLoading" border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="规则名称" align="center">
          <template slot-scope="scope">{{scope.row.roleName}}</template>
        </el-table-column>
        <el-table-column label="规则编号" align="center">
          <template slot-scope="scope">{{scope.row.roleCode}}</template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">{{scope.row.createTime}}</template>
        </el-table-column>
        <el-table-column label="活动开始时间" align="center">
          <template slot-scope="scope">{{scope.row.beginTime}}</template>
        </el-table-column>
        <el-table-column label="活动结束时间" align="center">
          <template slot-scope="scope">{{scope.row.endTime}}</template>
        </el-table-column>
        <el-table-column label="客户端类型" align="center">
          <template slot-scope="scope">{{scope.row.clientId | clientStatus}}</template>
        </el-table-column>
        <el-table-column label="注册赠送最小积分" align="center">
          <template slot-scope="scope">{{scope.row.regMinScore}}</template>
        </el-table-column>
        <el-table-column label="注册赠送上限积分" align="center">
          <template slot-scope="scope">{{scope.row.regMaxScore}}</template>
        </el-table-column>
        <el-table-column label="积分过期时间" align="center">
          <template slot-scope="scope">{{scope.row.dateNum}}{{scope.row.dateType|dateTypeDetail}}</template>
        </el-table-column>
        <el-table-column label="派发总上限" align="center">
          <template slot-scope="scope">{{scope.row.maxTotalScore}}</template>
        </el-table-column>
        <el-table-column label="单日派发上限" align="center">
          <template slot-scope="scope">{{scope.row.dayTotalScore}}</template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">{{scope.row.status | ListStatus}}</template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleEditSort(scope.$index, scope.row)">修改积分
            </el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select size="small" v-model="operateType" placeholder="批量操作">
        <el-option v-for="item in operates" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button style="margin-left: 20px" class="search-button" @click="handleBatchOperate()" type="primary"
        size="small">
        确定
      </el-button>
    </div>
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper" :page-size="listQuery.pageSize" :page-sizes="[5,10,15]"
        :current-page.sync="listQuery.pageNum" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="创建注册积分活动" :visible.sync="selectDialogVisible" width="50%" :destroy-on-close='true'>
      <el-form :model="intergralForm" :rules="intergralFormRules" status-icon ref="intergralForm" label-width="120px"
        class="demo-ruleForm">
        <el-form-item label="规则名称" prop="roleName">
          <el-input v-model="intergralForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="客户端类型" prop="clientId">
          <el-select v-model="intergralForm.clientId" placeholder="请选择活动区域" style="width:100%">
            <el-option label="所有类型" value="ALL"></el-option>
            <el-option label="微信" value="WX"></el-option>
            <el-option label="app" value="APP"></el-option>
            <el-option label="网页" value="WEB"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最小积分" prop="regMinScore">
          <el-input v-model="intergralForm.regMinScore"></el-input>
        </el-form-item>
        <el-form-item label="上限积分" prop="regMaxScore">
          <el-input v-model="intergralForm.regMaxScore"></el-input>
        </el-form-item>
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker v-model="activityTime" type="datetimerange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" style="width:100%" 
            :picker-options="pickerOptions" @input='changeTimePicker'>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="积分过期时间" prop="dateNum">
          <el-input placeholder="请输入内容" v-model="intergralForm.dateNum" class="input-with-select">
            <el-select v-model="intergralForm.dateType" slot="append" placeholder="请选择">
              <el-option label="小时" value="0"></el-option>
              <el-option label="天" value="1"></el-option>
              <el-option label="月" value="2"></el-option>
              <el-option label="年" value="3"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="派发总上限" prop="maxTotalScore">
          <el-input v-model="intergralForm.maxTotalScore"></el-input>
        </el-form-item>
        <el-form-item label="单日派发上限" prop="dayTotalScore">
          <el-input v-model="intergralForm.dayTotalScore"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <!-- <el-input v-model="intergralForm.status"></el-input> -->
          <el-select v-model="intergralForm.status" placeholder="请选择" style="width: 100%;">
            <el-option label="有效" value="1"></el-option>
            <el-option label="无效" value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item> -->
      </el-form>
      <div style="clear: both;"></div>
      <div slot="footer">
        <el-button size="small" @click="selectDialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { fetchList, deleteIntegral, updateIntegralProduct, createIntegral, fetchQuoteProduct } from '@/api/integral';
  import { fetchList as fetchProductList } from '@/api/product';
  import { validatInteger } from '@/utils/validate';
  import { ruleName, regMinScore, regMaxScore, maxTotalScore, dayTotalScore, dateNum } from './utils/rule';
  import moment from 'moment';
  const defaultListQuery = {
    pageNum: 1,
    pageSize: 5,
    roleName: '',
    clientId: '',
    status: '2',
  };
  const defaultRecommendOptions = [
    {
      label: '未推荐',
      value: 0
    },
    {
      label: '推荐中',
      value: 1
    }
  ];
  export default {
    name: 'hotProductList',
    data() {
      // 数字限定
      let isInteger = (rule, value, callback, text) => {
        if (value === '') {
          callback(new Error(text + '不能为空'));
        } else {
          if (!validatInteger(value)) {
            callback(new Error(text + '只能为大于零的整数'));
          }
          callback();
        }
      };
      // let ruleName = (rule, value, callback,text) => {
      //   if (value === '') {
      //     callback(new Error(text+'不能为空'));
      //   } else {
      //     if (!validatInteger(value)) {
      //       callback(new Error(text+'只能为大于零的整数'));
      //     }
      //     callback();
      //   }
      // };
      return {
        listQuery: Object.assign({}, defaultListQuery),
        recommendOptions: Object.assign({}, defaultRecommendOptions),
        integralList: null,
        total: null,
        listLoading: false,
        multipleSelection: [],
        type: 1,
        activityTime:[],
        operates: [
          {
            label: "删除",
            value: 1
          }
        ],
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        operateType: null,
        selectDialogVisible: false,
        dialogData: {
          list: null,
          total: null,
          multipleSelection: [],
          listQuery: {
            keyword: null,
            pageNum: 1,
            pageSize: 5
          }
        },
        isCreate: true,
        sortDialogData: { dayNum: '', limitNum: '', ids: [] },
        // 创建表单数据源
        intergralForm: { dateType: '0', clientId: '', roleName: '', regMinScore: '', regMaxScore: '', maxTotalScore: '', dayTotalScore: '', dateNum: '', activityTime: [], status: 1 },
        sortChSGoodsData: { dayNum: '', limitNum: '' },
        sortRules: {
          dayNum: [
            {
              required: true, validator: (rule, value, callback) => {
                isInteger(rule, value, callback, '限购时间')
              }, trigger: 'blur'
            }
          ],
          limitNum: [
            {
              required: true, validator: (rule, value, callback) => {
                isInteger(rule, value, callback, '限购数量')
              }, trigger: 'blur'
            }
          ],
        },
        intergralFormRules: {
          roleName: [
            {
              required: true, validator: (rule, value, callback) => {
                ruleName(rule, value, callback, '规则名称')
              }, trigger: 'blur'
            }
          ],
          dateNum: [
            {
              required: true, validator: (rule, value, callback) => {
                dateNum(rule, value, callback, '积分过期时间')
              }, trigger: 'blur'
            }
          ],
          regMinScore: [
            {
              required: true, validator: (rule, value, callback) => {
                regMinScore(rule, value, callback, this.intergralForm.regMaxScore, () => {
                  // this.$refs.intergralForm.validateField('regMaxScore')
                })
              }, trigger: 'blur'
            }
          ],
          regMaxScore: [
            {
              required: true, validator: (rule, value, callback) => {
                regMaxScore(rule, value, callback, this.intergralForm.regMinScore, () => {
                  //  this.$refs.intergralForm.validateField('regMinScore')
                })
              }, trigger: 'blur'
            }
          ],
          maxTotalScore: [
            {
              required: true, validator: (rule, value, callback) => {
                maxTotalScore(rule, value, callback, this.intergralForm.dayTotalScore, () => {
                  //  this.$refs.intergralForm.validateField('dayTotalScore')
                })
              }, trigger: 'blur'
            }
          ],
          dayTotalScore: [
            {
              required: true, validator: (rule, value, callback) => {
                dayTotalScore(rule, value, callback, this.intergralForm.maxTotalScore, () => {
                  //    this.$refs.intergralForm.validateField('maxTotalScore')
                })
              }, trigger: 'blur'
            }
          ],
          activityTime: [
            { required: true, message: '请输入活动时间', trigger: 'blur' }
          ],
          clientId: [
            { required: true, message: '请选择客户端', trigger: 'blur' }
          ],
          dateType: [
            { required: true, message: '请选择单位', trigger: 'blur' }
          ],
          status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
        }
      }
    },
    created() {
      this.getList();
    },
    filters: {
      clientStatus(status) {
        if (status === 'APP') {
          return 'APP';
        } else if (status === 'WEB') {
          return '网页';
        } else if (status === 'ALL') {
          return '所有平台';
        } else if (status === 'WX') {
          return '微信';
        }
      },
      ListStatus(status) {
        if (status == 0) {
          return '无效';
        } else if (status == 1) {
          return '有效';
        }
      },
      dateTypeDetail(status) {
        if (status == 0) {
          return '小时';
        } else if (status == 1) {
          return '天';
        } else if (status == 2) {
          return '月';
        } else if (status == 3) {
          return '年';
        }
      }
    },
    methods: {
      submitForm() {
        this.$refs['intergralForm'].validate((valid) => {
          if (valid) {
            if (this.isCreate) {
              this.editorIntergral()
            } else {
              this.$confirm('是否要修改属性?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.editorIntergral()
              });
            }
          } else {
            return false;
          }
        });
      },
      changeTimePicker(e){
        this.$set(this.intergralForm, "activityTime", [e[0], e[1]]);
      },
      // 添加修改积分
      editorIntergral() {
        let msg = this.isCreate ? '添加' : '修改';
        let intergralForm = {};
        for (let i in this.intergralForm) {
          if (i != 'activityTime') {
            intergralForm[i] = this.intergralForm[i]
          }
        }
        intergralForm.beginTime = moment(this.activityTime[0]).format('YYYY-MM-DD HH:mm:ss');
        intergralForm.endTime = moment(this.activityTime[1]).format('YYYY-MM-DD HH:mm:ss');
        if (this.isCreate) {
          createIntegral(intergralForm).then(data => {
            this.selectDialogVisible = false;
            this.getList();
            // this.sortDialogData.dayNum = '';
            // this.sortDialogData.limitNum = '';
            this.$message({
              type: 'success',
              message: msg + '成功'
            });
          });
        } else {
          updateIntegralProduct(intergralForm).then(data => {
            this.selectDialogVisible = false;
            this.getList();
            // this.sortDialogData.dayNum = '';
            // this.sortDialogData.limitNum = '';
            this.$message({
              type: 'success',
              message: msg + '成功'
            });
          });
        }
      },
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },

      handleDelete(index, row) {
        this.deleteIntegral([row.id]);
      },
      handleBatchOperate() {
        if (this.multipleSelection < 1) {
          this.$message({
            message: '请选择一条记录',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        let ids = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id);
        }
        if (this.operateType == 1) {
          //删除
          this.deleteIntegral(ids);
        } else {
          this.$message({
            message: '请选择批量操作类型',
            type: 'warning',
            duration: 1000
          });
        }
      },
      createActivity() {
        this.selectDialogVisible = true;
        this.isCreate = true;
        this.intergralForm = { clientId: '', roleName: '', regMinScore: '', regMaxScore: '', maxTotalScore: '', dayTotalScore: '', dateNum: '',  dateType: '0' }
        // this.getDialogList();
      },
      handleSelectSearch() {
        this.getDialogList();
      },
      handleDialogSizeChange(val) {
        this.dialogData.listQuery.pageNum = 1;
        this.dialogData.listQuery.pageSize = val;
        this.getDialogList();
      },
      handleDialogCurrentChange(val) {
        this.dialogData.listQuery.pageNum = val;
        this.getDialogList();
      },
      handleDialogSelectionChange(val) {
        this.dialogData.multipleSelection = val;
      },
      handleEditSort(index, row) {
        // console.log('row',row)
        this.selectDialogVisible = true;
        this.isCreate = false;
        // console.log(this.integralList)
        row.status = row.status.toString();
        row.dateType = row.dateType.toString();
        this.intergralForm = row;
        this.$set(this.intergralForm, "activityTime", [new Date(row.beginTime), new Date(row.endTime)]);
        this.activityTime = [new Date(row.beginTime), new Date(row.endTime)];
        this.intergralForm.id = row.id;
        // console.log('intergralForm',this.intergralForm)
        // this.type = 1;
        // this.sortDialogVisible=true;
        // this.sortDialogData.sort=row.sort;
        // this.sortDialogData.ids=[row.id];
      },
      getList() {
        this.listLoading = true;
        for (let i in this.listQuery) {
          if (this.listQuery[i] == '' || !this.listQuery[i]) {
            delete this.listQuery[i]
          }
        }
        let query = { ...this.listQuery }
        if (query.status == '2') {
          delete query.status;
        }

        fetchList(query).then(data => {
          this.listLoading = false;
          this.integralList = data.info;
          this.total = data.totalnum;
        })
      },
      deleteIntegral(ids) {
        this.$confirm('是否要删除积分?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = { id: ids }
          deleteIntegral(data).then(data => {
            this.getList();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          });
        })
      },
      getDialogList() {
        fetchQuoteProduct(this.dialogData.listQuery).then(data => {
          this.dialogData.list = data.info;
          this.dialogData.total = data.totalnum;
        })
      }
    }
  }
</script>
<style>
  .input-with-select .el-input-group__append {
    background-color: #fff;
  }

  .input-with-select .el-select .el-input {
    width: 130px;
  }
</style>